from datetime import datetime, timedelta

from sqlalchemy import desc

def select_document_list(args):
    from ..model.document_model import Document
    list = Document.query.all()
    return list

def select_document_page(args):
    from ..model.document_model import Document
    document_name = args.get("document_name")
    document_type = args.get("document_type")
    upload_time = args.get("upload_time")
    current_page = int(args.get("current_page"))
    page_size = int(args.get("page_size"))

    query = Document.query
    total = query.count()
    pages = (total + page_size - 1) // page_size

    if document_name:
        query = query.filter(Document.document_name.like(f"%{document_name}%"))

    if document_type:
        query = query.filter(Document.document_type == document_type)

    if upload_time:
        target_date = datetime.strptime(upload_time, '%Y-%m-%d').date()
        start_date = datetime.combine(target_date, datetime.min.time())
        end_date = start_date + timedelta(days = 1)
        query = query.filter(Document.upload_time >= start_date, Document.upload_time < end_date)

    list = []
    records = query.order_by(desc(Document.upload_time)).offset(current_page * page_size).limit(page_size).all()
    for record in records:
        item = record.to_dict()
        if item["upload_time"]:
            item["upload_time"] = item["upload_time"].strftime('%Y-%m-%d %H:%M:%S')
        list.append(item)
    return { "total": total, "pages": pages, "records": list }

def insert_row(document):
    from ... import db
    db.session.add(document)
    db.session.commit()

def delete_row(document):
    from ... import db

    if document:
        db.session.delete(document)
        db.session.commit()

def select_document_by_number(number):
    from ..model.document_model import Document
    document = Document.query.filter(Document.library_number == number).first()
    return document
